/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package syncmellariusnote.helpers;

/**
 *
 * @author Vitor
 */
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import syncmellariusnote.SyncMellariusNot;


public class ConnectorConfigurator {

    // TCP Socket
    static Socket  socket;
    static ServerSocket server;
    int TIMEOUT = 100000;


   
    public static Socket getClientConnection() {
        return socket;
    }
    public static ServerSocket getServerConnection() {
        return server;
    }
    public void execAdb() {
        // run the adb bridge

        try {
           
            Process p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\adt-bundle-SDK\\sdk\\platform-tools\\adb.exe forward tcp:38300 tcp:38300");
            Scanner sc = new Scanner(p.getErrorStream());
            if (sc.hasNext()) {
                while (sc.hasNext()) {
                    System.out.println(sc.next());
                }
                System.out.println("Cannot start the Android debug bridge");
            }
        } catch (Exception e) {
            System.out.println("fatalError" + (e.toString()));
        }
    }

   public void initializeConnection() {
//Create socket connection
        try {   
             if(SyncMellariusNot.getConnectionType()){
            server = new ServerSocket(SyncMellariusNot.getPort());
            server.setSoTimeout(TIMEOUT);
            System.out.println("*******************************");
            System.out.println("* Click Syn on Mellarius Note *");
            socket = server.accept();
            }else{
            socket = new Socket("localhost", SyncMellariusNot.getPort());
            Thread closeSocketOnShutdown = new Thread() {
                public void run() {
                    try {
                        socket.close();
                    } catch (IOException e) {
                    }
                }
            };
            Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
            }
            
// add a shutdown hook to close the socket if system crashes or exists unexpectedly
            

        } catch (UnknownHostException e) {
        } catch (IOException e) {
        }
    }
}
